package icu.which.strongchild.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import icu.which.strongchild.common.ErrorCode;
import icu.which.strongchild.common.ResultUtils;
import icu.which.strongchild.constant.UserConstant;
import icu.which.strongchild.exception.BusinessException;
import icu.which.strongchild.model.domain.User;
import icu.which.strongchild.model.vo.UserVO;
import icu.which.strongchild.service.UserService;
import icu.which.strongchild.mapper.UserMapper;
import icu.which.strongchild.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static icu.which.strongchild.constant.UserConstant.CURRENT_USER;
import static icu.which.strongchild.constant.UserConstant.SALT;


/**
 * @author which
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-03-01 00:12:41
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(UserVO user) {
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public UserVO userLogin(String userAccount, String password, HttpServletRequest request) {
        /*
         * 校验空
         * 校验参数
         * 加密
         * 查询用户
         * 登录态
         * 脱敏
         * */
        if (StringUtils.isAnyBlank(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码为空");
        }

        // TODO: 2023/3/1 检验空

        String safePassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount);
        qw.eq("userPassword", safePassword);
        User user = this.userMapper.selectOne(qw);
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGIN_FAIL);
        }

        UserVO res = UserVO.getUserVO(user);
        request.getSession().setAttribute(CURRENT_USER, res);
        return res;
    }

    @Override
    public boolean logout(HttpServletRequest httpServletRequest) {
        httpServletRequest.getSession().removeAttribute(CURRENT_USER);
        return true;
    }

    @Override
    public UserVO getLoginUser(HttpServletRequest httpServletRequest) {
        UserVO currentUser = (UserVO) httpServletRequest.getSession().getAttribute(CURRENT_USER);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return currentUser;
    }

    @Override
    public boolean register(String userAccount, String password) {
        //检验空
        if (StringUtils.isAnyBlank(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // TODO: 2023/3/1 校验合法
        //业务
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
//        long count = userMapper.selectCount(queryWrapper);
        // TODO: 2023/3/1 优化 
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        return result;
    }

    @Override
    public boolean deleteUser(Long id, HttpServletRequest request) {
        if (id == null || request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (id <= 0) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        if (this.isAdmin(request)) {
            return this.removeById(id);
        } else {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
    }

    @Override
    public boolean updateUser(User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (user.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 补充校验，如果用户没有传任何要更新的值，就直接报错，不用执行 update 语句
        // 如果是管理员，允许更新任意用户
        // 如果不是管理员，只允许更新当前（自己的）信息
        UserVO currentUser = this.getLoginUser(request);
        if (currentUser.getUserRole() != 3 || user.getId() != currentUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User oldUser = userMapper.selectById(user.getId());
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return this.updateById(user);
    }

    @Override
    public List<UserVO> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 1. 先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        // 2. 在内存中判断是否包含要求的标签
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            //用户的标签可能为空
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(UserVO::getUserVO).collect(Collectors.toList());
    }

    @Override
    public List<UserVO> recommondUserByTags(long num, HttpServletRequest request) {
        UserVO attribute = (UserVO)request.getSession().getAttribute(CURRENT_USER);
        if(attribute == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        //搜索全部用户id 和tags
        String tags = attribute.getTags();
        Gson gson = new Gson();
        //得到当前用户的标签列表
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {}.getType());
        // 用户，和每个用户的相似度
        List<Pair<User,Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || user.getId() == attribute.getId()) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {}.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        //实际 List<User> 大小就是1，由于groupingByID带来的
        Map<Long, List<UserVO>> collect = this.list(userQueryWrapper)
                .stream()
                .map(User::getUserVO)
                .collect(Collectors.groupingBy(UserVO::getId));
        List<UserVO> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(collect.get(userId).get(0));
        }
        return finalUserList;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        UserVO userVO = (UserVO) request.getSession().getAttribute(CURRENT_USER);
        if (userVO == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (userVO.getUserRole() != 3) {
            return false;
        } else {
            return true;
        }
    }
}




